package com.enba.boot.core.context;

import cn.hutool.core.convert.Convert;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.TypeReference;
import com.alibaba.ttl.TransmittableThreadLocal;
import com.enba.boot.core.constants.SysConst;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/** 用户信息上下文Holder */
public class SecurityContextHolder {

  private static final TransmittableThreadLocal<Map<String, Object>> THREAD_LOCAL =
      new TransmittableThreadLocal<>();

  public static Map<String, Object> getLocalMap() {
    Map<String, Object> map = THREAD_LOCAL.get();
    if (map == null) {
      map = new ConcurrentHashMap<>();
      THREAD_LOCAL.set(map);
    }
    return map;
  }

  public static void setLocalMap(Map<String, Object> threadLocalMap) {
    THREAD_LOCAL.set(threadLocalMap);
  }

  public static void setKeyValue(String key, Object value) {
    Map<String, Object> map = getLocalMap();
    map.put(key, value);
  }

  public static Object getValue(String key) {
    Map<String, Object> map = getLocalMap();
    return map.get(key);
  }

  public static <T> T getValue(String key, Class<T> clazz) {
    Map<String, Object> map = getLocalMap();
    return JSON.parseObject(JSON.toJSONString(map.get(key)), clazz);
  }

  public static <T> T getValue(String key, TypeReference<T> typeReference) {
    Map<String, Object> map = getLocalMap();
    return JSON.parseObject(JSON.toJSONString(map.get(key)), typeReference);
  }

  public static void remove() {
    THREAD_LOCAL.remove();
  }

  /**
   * 设置用户ID
   *
   * @param userId 用户ID
   */
  public static void setUserId(String userId) {
    setKeyValue(SysConst.USER_ID, userId);
  }

  /**
   * 获取用户ID
   *
   * @return 用户ID
   */
  public static Long getUserId() {
    Object value = getValue(SysConst.USER_ID);
    return Convert.toLong(value, 0L);
  }
}
